import React,{useState,useEffect} from 'react'
import $http from '../../api/http'
import {Table,Button,Space,Pagination} from 'antd'
export default function ProductsByPage() {
  const defaultImg="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fku.90sjimg.com%2Felement_pic%2F17%2F04%2F20%2Fa92c90db521eacb41337f87e3b9b77c4.jpg&refer=http%3A%2F%2Fku.90sjimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1666943191&t=e886a5e903254b423b0bb1ef0a005dd4"
  const [list,setList]=useState([])
  const [total,setTotal]=useState(0)
  const [pageSize,setPageSize]=useState(10)
  const [currentPage,setCurrentPage]=useState(1)
  const getProductsByPage=async(params={pageNo:1,pageSize:5})=>{
    const {data:{total,pageSize,data,currentPage}}=await $http.products.findGoodsByPage(params)
    setList(data)
    setTotal(total)
    setPageSize(pageSize)
    setCurrentPage(~~currentPage)
  }
  useEffect(()=>{
    getProductsByPage()
  },[])

  const onChange=(pageNo)=>{
    setCurrentPage(pageNo)
    getProductsByPage({pageNo,pageSize:5})
  }

  const onSizeChange=(current,pageSize)=>{
    console.log('current',current);
    console.log('pageSize',pageSize);
    getProductsByPage({current,pageSize})
  }



  const columns=[
    {
      title:'名称',
      dataIndex:'name' //如果要获取集合中的数据，这里是和集合中对象中的属性名对象的
    },
    {
      title:'价格',
      dataIndex:'price'
    },
    {
      title:'标题',
      dataIndex:'title'
    },
    {
      title:'分类',
      dataIndex:'type',
      render:(records)=>{
        if(records){
          return records.name
        }
      }
    },
    {
      title:'图片',
      dataIndex:'imgSrc',
      render:(records)=>{
        if(records){
          return <img src={records} style={{width:'50px'}}></img>
        }else{
          return <img src={defaultImg} style={{width:'50px'}}></img>
        }
      }
    },
    {
      title:'操作',
      dataIndex:'action',
      render:()=>{
          return(
            <Space>
              <Button type='primary'>查看</Button>
              <Button type='primary' danger>删除</Button>
            </Space>
          )
      }
    }
  ]
  return (
    <div>
       <Table 
          rowKey={"_id"}
          dataSource={list}
          columns={columns}
          pagination={false}>
       </Table>
       <Pagination 
            total={total} 
            pageSize={pageSize} 
            onChange={onChange}
            current={currentPage}
            showSizeChanger={true}
            onShowSizeChange={onSizeChange}
            pageSizeOptions={[3,5,10,15]}></Pagination>

    </div>
  )
}
